//
//  OAuthViewController.swift
//  nimabi
//
//  Created by danny on 15/6/26.
//  Copyright © 2015年 DannyLiu. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController,UIWebViewDelegate {
    
    // 定义常量
    private let Wb_client_id =	"1418272428"
    private let Wb_redirect_uri = "https://www.baidu.com"
    private let WB_App_Secret       = "b64b90fd8c26764620df752308e7a544"


    
    
    
    //定义一个uiwebview
    lazy var webview : UIWebView? = {
        let v = UIWebView()
        v.delegate = self
        
        return v
    }()
    
    
    override func loadView() {
        
        // 跟试图就是webview
        view = webview
        
        // 设置nav属性
        title = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        

    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 加载授权页面
        loadOAuthPage()
    }
    
    
    // 关闭本页 的方法
    func close(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // 加载页面的方法
    private func loadOAuthPage(){
        
        //  授权url地址
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(Wb_client_id)&redirect_uri=\(Wb_redirect_uri)"
        let url = NSURL(string: urlString)!
        
        webview?.loadRequest(NSURLRequest(URL: url))
    }
    
    
    // webView的代理方法
    /*

    <NSMutableURLRequest: 0x7f8d1e072d10> { URL: https://api.weibo.com/oauth2/authorize }
    <NSMutableURLRequest: 0x7f8d1e10e700> { URL: https://www.baidu.com/?code=27b9176a96418b8c2ec7464e4016d4f3 }
    */
    
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        print("加载页面是否拦截")
        
        // 设置url的完整字符串
        let urlString = request.URL!.absoluteString
        
        if !urlString.hasPrefix(Wb_redirect_uri){
            return true
        }
        
        print("加载页面已被拦截!!!!!!!!!")

        
//        // 判断是否包含code=
//        let codestr = "code="
//        if (urlString?.rangeOfString(codestr) != nil) {
//            let code = urlString!.substringFromIndex(codestr.endIndex, 0)
//            
//            print(code)
//        
//        }
        
        // 获取请求 URL 中的 查询字符串
        let query = request.URL!.query!
        let codeStr = "code="
        
        // 判读是否包含 code=
        if query.hasPrefix(codeStr) {
            let code = query.substringFromIndex(advance(codeStr.endIndex, 0))
            print("获取授权码 \(code)")
            loadAccessToken(code)
            
        } else {
            print("取消授权")
            // 关闭窗口
            close()
        }

        return false
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showInfoWithStatus("伦家正在用力加载呢...")
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    
    private func loadAccessToken(code:String){
        // 1 设置url
        let url = "oauth2/access_token"
        
        // 2 设置参数
        let params = ["client_id": Wb_client_id,
            "client_secret": WB_App_Secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": Wb_redirect_uri]
        
        // 3 异步发送请求
        NetWorkingTools.sharedNetWorkingTools().POST(url, parameters: params, success: { (_, json) -> Void in
            
            UserAccount(dict: json as! [String: AnyObject]).loadUserInfo{ (account, error) -> () in
                
                // 判断信息是否正确
                if account != nil {
                    
                    // 1 设置全局的account
                    sharedUserAccount = account

                    // 2 发送通知
                    NSNotificationCenter.defaultCenter().postNotificationName(HMSwitchRootVCNotification, object: false)
                    
                    self.close()
                    
                    return
               }
                print(error)
                
                SVProgressHUD.showInfoWithStatus("什么破网,用户为空")
                
            }
            }){ (_, error) -> Void in
                print(error)
                SVProgressHUD.showInfoWithStatus("什么破网,授权为空")

        }
        
    }
    
}
